package edu.neu.agv_backend.exception;

import edu.neu.agv_backend.dto.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.RestClientException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public AjaxResult<Void> handleBiz(BusinessException ex) {
        log.warn("Business exception: {}", ex.getMessage());
        AjaxResult<Void> res = new AjaxResult<>();
        res.setCode(ex.getCode());
        res.setMsg(ex.getMessage());
        return res;
    }

    @ExceptionHandler({RestClientException.class})
    public AjaxResult<Void> handleRest(RestClientException ex) {
        log.error("Remote call error", ex);
        AjaxResult<Void> res = new AjaxResult<>();
        res.setCode(HttpStatus.BAD_GATEWAY.value());
        res.setMsg("Remote service error");
        return res;
    }

    @ExceptionHandler({MethodArgumentNotValidException.class, HttpMessageNotReadableException.class})
    public AjaxResult<Void> handleBadRequest(Exception ex) {
        log.warn("Bad request: {}", ex.getMessage());
        AjaxResult<Void> res = new AjaxResult<>();
        res.setCode(HttpStatus.BAD_REQUEST.value());
        res.setMsg("Invalid request parameters");
        return res;
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult<Void> handleOther(Exception ex) {
        log.error("Unexpected error", ex);
        AjaxResult<Void> res = new AjaxResult<>();
        res.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        res.setMsg("Internal server error");
        return res;
    }
} 